/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-04-19
 * Time: 16:27
 */
class MyBlockingQueue {
    private String[] data;
    private int head;
    private int tail;
    private int size;
    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }
    public void put(String elem){
        synchronized (this) {
            if (size > data.length) {
                //阻塞等待--待写
                return;
            }
            data[tail++] = elem;
            size++;
            if (tail >= data.length) {
                tail = 0;
            }
        }
    }
    public String take() {
        synchronized (this) {
            if (size == 0) {
                //阻塞等待--待写
                return null;
            }
            String ret = data[head++];
            size--;
            if(head >= data.length) {
                head = 0;
            }
            return ret;
        }
    }
}
public class Demo43 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread producer = new Thread(() -> {
            int n = 0;
            while(true) {
                queue.put(n + "");
                System.out.println("生产元素：" + n);
                n++;
            }
        });
        Thread consumer = new Thread(() -> {
            while(true) {
                String value = queue.take();
                System.out.println("消费元素：" + value);
            }
        });
        producer.start();
        consumer.start();
    }
}
